package services

import (
	"fmt"
	"sync"

	"cdk.tf/go/stack/interfaces"
	"cdk.tf/go/stack/utils"
	"github.com/aws/constructs-go/constructs/v10"
	"github.com/aws/jsii-runtime-go"
	"github.com/cdktf/cdktf-provider-aws-go/aws/v17/vpc"
)

type VPCService struct {
	vpcs map[string]*vpc.Vpc
	mu   sync.RWMutex
}

func NewVPCService() *VPCService {
	return &VPCService{
		vpcs: make(map[string]*vpc.Vpc),
	}
}

func (s *VPCService) CreateVPC(scope constructs.Construct, id string, config *interfaces.VPCConfig) (*vpc.Vpc, error) {
	// 验证CIDR块格式
	if !isValidCIDR(config.CidrBlock) {
		return nil, fmt.Errorf("invalid CIDR block: %s", config.CidrBlock)
	}

	vpcResource := vpc.NewVpc(scope, jsii.String(id), &vpc.VpcConfig{
		CidrBlock:          jsii.String(config.CidrBlock),
		EnableDnsHostnames: jsii.Bool(true),
		EnableDnsSupport:   jsii.Bool(true),
		InstanceTenancy:    jsii.String("default"),
		Tags:               utils.ConvertTags(config.Tags),
	})

	// 添加名称标签
	if config.Name != "" {
		vpcResource.AddOverride(jsii.String("tags.Name"), jsii.String(config.Name))
	}

	s.mu.Lock()
	vpcID := utils.SafeDereference(vpcResource.Id())
	if vpcID != "" {
		s.vpcs[vpcID] = &vpcResource
	}
	s.mu.Unlock()

	return &vpcResource, nil
}

func (s *VPCService) GetVPCByID(scope constructs.Construct, vpcID string) (*vpc.Vpc, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	if vpcResource, exists := s.vpcs[vpcID]; exists {
		return vpcResource, nil
	}

	return nil, fmt.Errorf("VPC with ID %s not found", vpcID)
}

func (s *VPCService) ListVPCs() map[string]*vpc.Vpc {
	s.mu.RLock()
	defer s.mu.RUnlock()

	result := make(map[string]*vpc.Vpc)
	for id, vpc := range s.vpcs {
		result[id] = vpc
	}
	return result
}

func (s *VPCService) GetVPCsByTags(tags map[string]string) map[string]*vpc.Vpc {
	s.mu.RLock()
	defer s.mu.RUnlock()

	result := make(map[string]*vpc.Vpc)
	for id, vpcResource := range s.vpcs {
		if s.vpcMatchesTags(vpcResource, tags) {
			result[id] = vpcResource
		}
	}
	return result
}

func (s *VPCService) vpcMatchesTags(vpcResource *vpc.Vpc, tags map[string]string) bool {
	// 简化实现，实际中需要检查VPC的标签
	// 这里假设所有VPC都匹配无标签查询
	return len(tags) == 0
}

// 辅助函数
func isValidCIDR(cidr string) bool {
	// 简单的CIDR验证
	if len(cidr) < 7 || len(cidr) > 18 {
		return false
	}
	return true
}
